import { getUserId } from '@/utils/auth'
import Layout from '@/layout'
import { getMenuPermissionApi, getMenuPermission2Api } from '@/api/menu'
const modules = import.meta.glob('@/views/**/*.vue')

export function filterAsyncRoutes(routes, parent) {
  const res = []

  for (let route of routes) {
    // 去除按钮类型
    if (route.type == '2') {
      continue
    }

    let temp = {
      path: route.path,
      component: '',
      redirect: '',
      name: route.name,
      meta: {
        title: route.title,
        icon: route.icon,
        key: route.menuId
      },
      children: []
    }

    if (route.parentId === 0) {
      temp.component = Layout
    } else {
      let routerKey = `/src/views/${route.component}.vue`
      // temp.component = () => import(routerKey)
      temp.component = modules[routerKey]
    }

    if (route.children && route.children.length > 0) {
      // 是目录
      if (route.type == '0') {
        let parents = filterRedirect(route.menuId)
        temp.redirect = parents + '/' + route.children[0].path
      }
      temp.children = filterAsyncRoutes(route.children, route)
    }

    res.push(temp)
  }

  return res
}

let flattenArr = []
// 找父级
function filterRedirect(parentId) {
  let res = []

  const filter = (routes, parentId) => {
    routes.forEach(item => {
      if (item.menuId === parentId) {
        res.push(item.path)
        if (item.parentId !== 0) {
          filter(routes, item.parentId)
        }
      }
    })
  }

  filter(flattenArr, parentId)

  return res.reverse().join('/')
}

// 摊平数组
function flattenArray(arr) {
  let result = []
  arr.forEach(item => {
    if (Array.isArray(item.children) && item.children.length > 0) {
      result = result.concat(flattenArray(item.children))
    }
    result.push(item)
  })
  return result
}

const getDefaultState = () => {
  return {
    routes: []
  }
}

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_ROUTES: (state, payload) => {
    state.routes = payload
  }
}

const actions = {
  getPermissionMenuAction({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      let res = await getMenuPermissionApi({
        userId: getUserId()
      })
      if (res.success) {
        flattenArr = flattenArray(res.data)
        // console.log('🚀 - parents:', filterRedirect(33))
        let routes = filterAsyncRoutes(res.data)
        routes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', routes)
        resolve({ routes })
        return
      }
      reject()
    })
  },
  resetRoutes({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_ROUTES', [])
      resolve()
    })
  }
  // async getPermissionMenuAction2({ commit, state }) {
  //   let res = await getMenuPermission2Api({
  //     userId: getUserId()
  //   })
  //   console.log('getPermissionMenuAction2===', res)
  // }
}

export default {
  namespaced: true,
  state: getDefaultState(),
  mutations,
  actions
}
